﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

namespace hw3
{
    public partial class Data : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dotnetConnectionString"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void QueryButton_Click(object sender, EventArgs e)
        {
            string strSql = "select * from " + DropDownList1.SelectedValue.ToString();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = strSql;
            cmd.CommandType = CommandType.Text;
            DataSet ds = new DataSet();

            try
            {
                conn.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(strSql, conn);
                adapter.SelectCommand = cmd;
                adapter.Fill(ds, DropDownList1.SelectedValue.ToString());
                GridView1.DataSource = ds;
                GridView1.DataBind();
                conn.Close();
            }
            catch(Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            conn.Open();

            string[] fnArray = getFieldName(conn);
            string cell = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim();

            string updateSql = "update "+ DropDownList1.SelectedValue.ToString() + " set "+fnArray[1]+"='"
                + cell + "' where "+fnArray[0]+"='"
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
            SqlCommand sqlcom = new SqlCommand(updateSql, conn);
            sqlcom.ExecuteNonQuery();
            
            GridView1.EditIndex = -1;
            gridviewFill();
            conn.Close();
        }

        //获取列名函数
        string[] getFieldName(SqlConnection conn)
        {
            StringBuilder fieldNames = new StringBuilder();
            string[] restrictionValues = new string[4];
            restrictionValues[0] = null; // Catalog
            restrictionValues[1] = null; // Owner
            restrictionValues[2] = DropDownList1.SelectedValue.ToString(); // Table
            restrictionValues[3] = null; // Column

            DataTable dt = conn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictionValues);
            foreach (DataRow dr in dt.Rows)
            {
                fieldNames.Append(dr["column_name"].ToString() + ",");
            }
            string[] array = fieldNames.ToString().Split(',');
            return array;
        }

        //填充gridview
        void gridviewFill()
        {
            string strSql = "select * from " + DropDownList1.SelectedValue.ToString();
            SqlDataAdapter sqlda = new SqlDataAdapter(strSql, conn);
            DataSet ds = new DataSet();
            sqlda.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }

        protected void InsertButton_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Open();
                //获取表头字段名
                string[] fnArray = getFieldName(conn);


                string sql = "insert into "+DropDownList1.SelectedValue.ToString()+"("+fnArray[0]+","+fnArray[1]+") values('" + TextBox1.Text + "','" + TextBox2.Text + "')";

                SqlCommand sqlcom = new SqlCommand(sql, conn);
                sqlcom.ExecuteNonQuery();
                gridviewFill();
        
                conn.Close();

            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            conn.Open();

            string[] fnArray = getFieldName(conn);
            string deleteSql = "delete from " + DropDownList1.SelectedValue.ToString() + " where " + fnArray[0] + "='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
            SqlCommand sqlcom = new SqlCommand(deleteSql, conn);
            sqlcom.ExecuteNonQuery();

            gridviewFill();

            conn.Close();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            gridviewFill();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            gridviewFill();
        }
    }
}